package org.csu.jpetstore.web.servlet;

import org.csu.jpetstore.domain.Account;
import org.csu.jpetstore.domain.Cart;
import org.csu.jpetstore.domain.Item;
import org.csu.jpetstore.service.CartService;
import org.csu.jpetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


public class ViewCartServlet extends HttpServlet {

    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String SIGNON_FORM = "/WEB-INF/jsp/account/SignonForm.jsp";

    private CatalogService catalogService;
    private CartService cartService;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //Cart cart = (Cart)session.getAttribute("cart");
        Cart cart = new Cart();
        Account user = (Account) session.getAttribute("loginAccount");
        if(user != null) {
            String username = user.getUsername();
            //if (cart == null) {
            //cart = new Cart();
            cartService = new CartService();
            catalogService = new CatalogService();
            List<String> itemList = cartService.getItemList(username);
            for (int i = 0; i < itemList.size(); i++) {
                Item item = catalogService.getItem(itemList.get(i));
                int quantity = cartService.itemNum(itemList.get(i), username) - 1;
                cart.addItem(item, quantity);
            }
            session.setAttribute("cart", cart);
            //}
            request.getRequestDispatcher(VIEW_CART).forward(request, response);
        }
        else {
            request.getRequestDispatcher(SIGNON_FORM).forward(request,response);
        }
    }
}
